package com.qsl.juc.alternately_print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AlternatelyPrintLockCondition {

    public static void main(String[] args) {
        char[] digitalArr = "1234567".toCharArray();
        char[] letterArr = "ABCDEFG".toCharArray();
        Lock lock = new ReentrantLock();
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();

        new Thread(() -> {
            try {
                lock.lock();
                for (char digital : digitalArr) {
                    System.out.print(digital);
                    // t2.signal()、t1.await() 能否交换位置，为什么
                    c2.signal();    // 唤醒t2队列中等待的线程
                    c1.await();     // 进入t1队列自旋等待
                }
                // t2.signal() 能否去掉
                c2.signal();        // 避免有线程未被唤醒
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();

        new Thread(() -> {
            try {
                lock.lock();
                for (char letter : letterArr) {
                    System.out.print(letter);
                    // t1.signal()、t2.await() 能否交换位置，为什么
                    c1.signal();        //唤醒t1队列中等待的线程
                    c2.await();         //进入t2队列自旋等待
                }
                // t1.signal() 能否去掉
                c1.signal();            //避免有线程未被唤醒
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();
    }
}
